<?php
 
namespace StudyBuddy\Controllers;

use \StudyBuddy\Twitter;
use \StudyBuddy\WebPage;
use \StudyBuddy\Responder;
use \StudyBuddy\Request;

/**
 * This controller processes the form request
 * to post a message to Twitter
 * Right now we don't record any post
 * data to our database, just posting
 * the message to Twitter.
 *
 * It will post using the account of currently logged in user
 * if user does not have the Twitter token/secret then
 * there will be an exception thrown somewhere
 * and we will catch it here
 *
 */
class Tweet extends WebPage
{

	protected $aRequired = array('tweet', 'token');

	protected $bInitPageVars = false;
	
	protected $requireToken = true;
	
	protected $bRequirePost = true;

	/**
	 *
	 */
	protected function main(){

		if(!Request::isAjax()){
			e('Tweet called as non-ajax');
			throw new \StudyBuddy\Exception('This page can only be accessed using XHR request (ajax)');
		}

		try{
			$oTwitter = new Twitter($this->oRegistry);
			$aResponse = $oTwitter->prepareAndPost($this->oRequest->getUTF8('tweet'));
			Responder::sendJSON(array('tweet' => 'done'));
		} catch (\StudyBuddy\Exception $e){
			e('Unable to post message to Twitter: '.$e->getFile(). ' line: '.$e->getLine().' '.$e->getMessage());
			Responder::sendJSON(array('tweet' => 'error'));
		}
	}
}
